package com.admins.controller;

import com.commons.enums.ResponseCodeEnum;
import com.commons.utils.ResponseResult;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.admins.dto.UploadPicDto;
import com.admins.entity.Image;
import com.admins.service.ImageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author mis_wu
 * @date 2022/1/1 14:58
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/admins-pics")
@Api(tags = "图片上传与下载")
//nacos修改文件自动刷新(放在需要自动刷新的类上)
@RefreshScope
public class PicturesController {

    private static final Logger log = LoggerFactory.getLogger(PicturesController.class);

    @Value("${imgFilePath}")
    private String imgFilePath;

    @Value("${serverPath}")
    private String serverPath;

    @Resource
    private ImageService imageService;

    /**
     * 上传  FormData
     * @param uploadPicDto
     * @return
     */
    @ApiOperation("上传图片")
    @PostMapping("/uploadPic")
    public ResponseResult uploadPic(UploadPicDto uploadPicDto) throws IOException {
        String newName=System.currentTimeMillis()+uploadPicDto.getImgName();
        File fileDir = new File(imgFilePath);
        if (!fileDir.exists()){
            fileDir.mkdirs();
        }
        //前端判断不为空,后台不做判断 直接上传
        uploadPicDto.getPicture().transferTo(new File(fileDir,newName));
        //添加到数据库
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Image image = new Image(uploadPicDto.getImgId(),newName,serverPath+newName,"admin",new Date(),uploadPicDto.getImgDescript());
        int res = imageService.collectionImg(image);
        if (res!=1){
            return new ResponseResult(ResponseCodeEnum.UPLOAD_FAIL.getCode(), ResponseCodeEnum.UPLOAD_FAIL.getMsg());
        }
        return new ResponseResult(ResponseCodeEnum.UPLOAD_SUCCESS.getCode(),ResponseCodeEnum.UPLOAD_SUCCESS.getMsg());
    }
    /**
     * 图片下载
     * @param imgName
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/picDownload")
    @ApiOperationSupport(author = "wubo")
    @ApiOperation("根据图片名下载")
    public ResponseEntity<byte[]> picDownload(String imgName, HttpSession session) throws Exception {
        String path=session.getServletContext().getRealPath("/beautyPic");
        log.info("sessionPath:{},imgName:{}",path,imgName);
        HttpHeaders headers = new HttpHeaders();
        //headers.setContentType(MediaType.valueOf(MediaType.IMAGE_PNG_VALUE));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //设置下载本地的文件名
        //下载的文件名
        String fname= UUID.randomUUID().toString()+"--" +new Date().getTime()+imgName;
        headers.set("Content-Disposition", "attachment; filename="+fname);
        //获取服务器文件路径及文件
        File file = new File(path,imgName);
        if (file.exists()){
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                    headers, HttpStatus.OK);
        }else {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 查询
     * @param page
     * @param size
     * @param imgName
     * @param imgDesc
     * @return
     */
    @ApiOperation("分页查询获取图片列表")
    @GetMapping("/getImageListByPage/{page}/{size}")
    public ResponseResult getColImageList(@ApiParam("当前页") @PathVariable int page,@ApiParam("每页条数")  @PathVariable int size,@ApiParam("搜索图片名") String imgName,@ApiParam("搜索图片描述") String imgDesc){
        PageInfo<Image> pageinfo = imageService.getImagesListByPage(page, size, imgName, imgDesc);
        Map map=new HashMap();
        map.put("imageList",pageinfo.getList());
        map.put("totals",pageinfo.getTotal());
        return new ResponseResult(ResponseCodeEnum.SUCCESS.getCode(),ResponseCodeEnum.SUCCESS.getMsg(),map);
    }

    private String imgPath = "F:\\Vue项目模板\\cloud-admin\\static\\beautyPic\\1641554713082book4.jpg";
    @ApiOperation("下载文件测试API-success")
    @GetMapping("/test")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response, String fileFullName) throws UnsupportedEncodingException {
        String rootPath = imgFilePath;//这里是我在配置文件里面配置的根路径，各位可以更换成自己的路径之后再使用（例如：D：/test）
        String FullPath = rootPath + fileFullName;//将文件的统一储存路径和文件名拼接得到文件全路径
        File packetFile = new File(FullPath);
        String fileName = packetFile.getName(); //下载的文件名
        File file = new File(FullPath);
        // 如果文件名存在，则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the song successfully!");
            } catch (Exception e) {
                System.out.println("Download the song failed!");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {//对应文件不存在
            try {
                //设置响应的数据类型是html文本，并且告知浏览器，使用UTF-8 来编码。
                response.setContentType("text/html;charset=UTF-8");

                //String这个类里面， getBytes()方法使用的码表，是UTF-8，  跟tomcat的默认码表没关系。 tomcat iso-8859-1
                String csn = Charset.defaultCharset().name();

                System.out.println("默认的String里面的getBytes方法使用的码表是： " + csn);

                //1. 指定浏览器看这份数据使用的码表
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                OutputStream os = response.getOutputStream();

                os.write("对应文件不存在".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
